﻿using UnityEngine;

namespace ABA
{
    /// <summary>
    /// 具备Unity完整生命周期的单例
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class UnitySingleton<T> : MonoBehaviour where T : MonoBehaviour
    {
        private static T _inst;

        public static T inst
        {
            get
            {
                if (_inst == null)
                {
                    System.Type thisType = typeof(T);
                    string instName = thisType.Name;
                    GameObject go = SingletonManager.GetGameObject(instName);
                    if (go == null)
                    {
                        go = GameObject.Find($"/{instName}");
                        if (go == null)
                        {
                            go = new GameObject(instName);
                            go.transform.position = Vector3.zero;
                        }
                        SingletonManager.Retain(go);
                    }

                    if (go != null)
                    {
                        _inst = go.GetComponent<T>();
                        if (_inst == null)
                        {
                            _inst = go.AddComponent<T>();
                        }
                    }

                    if (_inst == null)
                    {
                        Debug.LogError($"Can't create UnitySingleton<{typeof(T)}>");
                    }
                }
                return _inst;
            }
        }

        public static T Active()
        {
            return inst;
        }

        public static bool IsValid
        {
            get
            {
                return _inst != null;
            }
        }

        private bool CheckInstance()
        {
            if (this == inst)
            {
                return true;
            }
            GameObject.Destroy(gameObject);
            return false;
        }

        protected virtual void OnLoad()
        {

        }

        public virtual void Awake()
        {
            if (CheckInstance())
            {
                OnLoad();
            }
#if UNITY_EDITOR
            Debug.Log($"UnitySingleton Instance:{typeof(T).Name}");
            GameObject g = SingletonManager.root;
            if (g != null)
            {
                this.gameObject.transform.SetParent(g.transform);
            }
#endif
        }

        protected virtual void OnDestroy()
        {
            Release();
        }

        public static void Release()
        {
            if (_inst != null)
            {
                SingletonManager.Release(_inst.gameObject);
                _inst = null;
            }
        }
    }
}